package com.wh.wisdomsite.xbox.client.service.configClient.us;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.wh.wisdomsite.xbox.ba.entity.Role;
import com.wh.wisdomsite.xbox.ba.service.IRoleService;
import com.wh.wisdomsite.xbox.client.session.ConfigClientSessionUser;
import com.wh.wisdomsite.xbox.common.Constants;
import com.wh.wisdomsite.xbox.common.annotation.NeedInSessionType;
import com.wh.wisdomsite.xbox.common.annotation.ServiceMethod;
import com.wh.wisdomsite.xbox.common.annotation.ServiceProvider;
import com.wh.wisdomsite.xbox.common.reponse.CommonResult;
import com.wh.wisdomsite.xbox.core.session.impl.SimpleSession;
import com.wh.wisdomsite.xbox.pojo.configClient.us.CclLoginIn;
import com.wh.wisdomsite.xbox.us.entity.*;
import com.wh.wisdomsite.xbox.us.service.*;
import com.wh.wisdomsite.xbox.utils.encrypt.md5.MD5Tool_Two;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 配置端用户 Service
 * @author 丁奕
 * @version V1.0
 * @Package com.wh.wisdomsite.xbox.client.service.configClient.us
 * @date 2018年11月2日 15:30
 * @Copyright 企业版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2018
 */
@ServiceProvider()
public class ConfigClientUserService {

    private static final Log logger = LogFactory.getLog(ConfigClientUserService.class);

    @Autowired
    private IUserService iUserService;

    @Autowired
    private ICompanyService iCompanyService;

    @Autowired
    private IRoleService iRoleService;

    @Autowired
    private IEmployeeService iEmployeeService;

    @Autowired
    private IHkUserService iHkUserService;

    @Autowired
    private IUserRoleService iUserRoleService;

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 配置段用户登陆
     * @param in
     * @return
     */
    @ServiceMethod(method = "zhgd.configClient.us.userLogin", title = "配置端用户登录", version = "1.0", needInSession = NeedInSessionType.NO)
    public CommonResult userLogin(CclLoginIn in){
        logger.info("配置端用户登录->>zhgd.configClient.us.userLogin->>开始");
        CommonResult commonResult = new CommonResult();
        try{
            //验证入参的登陆名
            if(StringUtils.isEmpty(in.getLoginName())){
                commonResult.setCode(Constants.CODE_FAIL);
                commonResult.setMessage("登录名称/手机号不能为空");
                return commonResult;
            }
            //账户密码
            if(StringUtils.isEmpty(in.getPassword())){
                commonResult.setCode(Constants.CODE_FAIL);
                commonResult.setMessage("登录密码不能为空");
                return commonResult;
            }
            //查询用户
            EntityWrapper<User> ewUser = new EntityWrapper<>();
            ewUser.setEntity(new User());
            if(StringUtils.isNotEmpty(in.getLoginName())){
                ewUser.eq("loginName", in.getLoginName());
                ewUser.or();
                ewUser.eq("userPhone", in.getLoginName());
            }
            List<User> userList = iUserService.selectList(ewUser);
            //验证查询list的个数是否正确
            if(userList == null || userList.size() == 0){
                commonResult.setCode(Constants.CODE_FAIL);
                commonResult.setMessage(Constants.ZHGD_CONFIG_LOGIN_USER_NOT_FIND);
                return commonResult;
            }
            if (userList.size() > 1) {
                commonResult.setCode(Constants.CODE_FAIL);
                commonResult.setMessage(Constants.ZHGD_CONFIG_LOGIN_LOGIN_NAME_FAIL);
                return commonResult;
            }
            //判断用户登录状态
            if(userList.get(0) != null){
                User user = userList.get(0);
                in.setPassword(MD5Tool_Two.MD5(in.getPassword()));
                //判断用户的禁用时间和禁用状态，若被禁用，且当前时间大于禁用时间，要恢复禁用状态
                if(user.getDisabledTime() != null && user.getDisabledTime().before(new Date()) && user.getLoginStatus().equals("2")){
                    //设置为启用
                    user.setLoginStatus("1");
                    //设置尝试次数为0
                    user.setPwdErrCount(0);
                    //设置禁用时间为null
                    user.setDisabledTime(null);
                }
                //状态为禁用用户,且禁用时间大于当前时间,不能登录(登录状态：1：可登录  2：已禁用)
                if(user.getLoginStatus().equals("2")){
                    commonResult.setCode(Constants.CODE_FAIL);
                    commonResult.setMessage("此用户已被禁用");
                    if(user.getDisabledTime() != null && user.getDisabledTime().after(new Date())){
                        commonResult.setMessage("此用户已被禁用，禁用截止时间为：" + simpleDateFormat.format(user.getDisabledTime()));
                    }
                    return commonResult;
                }
                //验证账户密码
                logger.info("配置端用户登录->>zhgd.configClient.us.userLogin->>passwordIn: " + in.getPassword());
                logger.info("配置端用户登录->>zhgd.configClient.us.userLogin->>passwordUser: " + user.getPassword());
                logger.info("配置端用户登录->>zhgd.configClient.us.userLogin->>是否相等: " + user.getPassword().equals(in.getPassword()));
                if(!in.getPassword().equals(user.getPassword())){
                    Integer pwdErrCount = user.getPwdErrCount();
                    commonResult.setCode(Constants.CODE_FAIL);
                    if(pwdErrCount == null){
                        pwdErrCount = 0;
                    }
                    user.setPwdErrCount(pwdErrCount + 1);
                    //判断是否超过错误次数
                    if(user.getPwdErrCount() < 5){
                        commonResult.setMessage("账号或密码错误,剩余"+(5-user.getPwdErrCount()) +"次尝试机会");
                    }else{
                        user.setLoginStatus("2");
                        user.setDisabledTime(new Date(new Date().getTime() + 60 * 60 * 24 * 1000));
                        commonResult.setMessage("账号或密码错误,已错误5次，账户被禁用，禁用时间截止至：" + simpleDateFormat.format(user.getDisabledTime()));
                    }
                    //更新user
                    iUserService.updateById(user);
                    return commonResult;
                }
                //存储会话用户
                String userId = user.getUsId();
                ConfigClientSessionUser cclSessionUser = getSessionUser(user);
                cclSessionUser.setSessionId(UUID.randomUUID().toString().replace("-",""));
                SimpleSession session = new SimpleSession();
                session.setAttribute(Constants.CONFIG_SESSION_USER, cclSessionUser);
                in.getXboxRequestContext().addSession(cclSessionUser.getSessionId(), session, 86400000 * 7, Constants.CONFIG_SESSION_USER);
                Map map = new HashMap();
                map.put("sessionId", cclSessionUser.getSessionId());
                map.put("userId", userId);
                map.put("userName", user.getLoginName());

                //登录成功
                commonResult.setCode(Constants.CODE_SUCCESS);
                commonResult.setMessage(Constants.CODE_SUCCESS_MSG);
                commonResult.setResult(map);
                //更新user
                user.setLoginDate(new Date());
                user.setLoginIp(in.getXboxRequestContext().getServletRequest().getRemoteAddr());
                user.setPwdErrCount(0);
                iUserService.updateById(user);
            }
            logger.info("配置端用户登录->>zhgd.configClient.us.userLogin->>结束");
        }catch (Exception e){
            logger.error("配置端用户登录->>zhgd.configClient.us.userLogin->>异常："+e.getMessage());
            commonResult.setCode(Constants.CODE_FAIL);
            commonResult.setMessage(Constants.CODE_FAIL_MSG);
            in.getXboxRequestContext().setException(new Exception(e.getMessage()));
            e.printStackTrace();
        }
        return commonResult;
    }

    /**
     * 一体化平台用户登录
     * @param in
     * @return
     */
    @ServiceMethod(method = "zhgd.configClient.us.ythUserLogin", title = "一体化平台端用户登录", version = "1.0", needInSession = NeedInSessionType.NO)
    public CommonResult ythUserLogin(CclLoginIn in){
        logger.info("一体化平台端用户登录->>zhgd.configClient.us.ythUserLogin->>开始");
        CommonResult commonResult = new CommonResult();
        try{

            //一体化平台入参登陆userJsonString
            String userJsonString = in.getUserJson();
            //验证入参的登陆名
            if(StringUtils.isEmpty(userJsonString)){
                commonResult.setCode(Constants.CODE_FAIL);
                commonResult.setMessage("登陆用户信息不能为空");
                return commonResult;
            }

            net.sf.json.JSONObject jsonResult = net.sf.json.JSONObject.fromObject(JSONObject.stringToValue(userJsonString));
            if(jsonResult.get("user") != null && !jsonResult.get("user").equals("")) {
                net.sf.json.JSONObject userJson = net.sf.json.JSONObject.fromObject(jsonResult.get("user"));
                //一体化账户登录
                EntityWrapper<User> ew = new EntityWrapper<User>();
                ew.setEntity(new User());
                ew.eq("openUid", userJson.get("id"));
                User user = iUserService.selectOne(ew);
                //判断本地是否有此条用户数据
                if (user == null) {
                    //本地未有此用户信息时,进行注册操作，注册后再进行登陆

                    //验证都通过，开始取出企业信息，根据企业ID查询是否已有此企业，若无则创建，有则返回此企业
                    net.sf.json.JSONObject companyJson = net.sf.json.JSONObject.fromObject(userJson.get("company"));
                    //根据企业ID查询
                    String ythCompanyId = companyJson.get("id").toString();
                    EntityWrapper<Company> ewCompany = new EntityWrapper<>();
                    ewCompany.setEntity(new Company());
                    ewCompany.eq("ythCompanyId", ythCompanyId);
                    Company company = iCompanyService.selectOne(ewCompany);
                    //若查询不到此企业，则创建
                    if (company == null) {
                        company = new Company();
                        //设置公司名称
                        company.setName(companyJson.get("name").toString());
                        company.setYthCompanyId(ythCompanyId);
                        company.setCompType("");
                        iCompanyService.saveCompany(company, null);
                    }
                    //保存用户信息
                    user = new User();
                    user.setLoginName("yth_" + userJson.get("loginName").toString());
                    user.setUserPhone(null);
                    user.setOpenUid(userJson.get("id").toString());
                    user.setCreateDate(new Date());
                    user.setPlatform("yth");
                    user.setCompanyId(company.getCompanyId());
                    //给密码加密,默认密码123456
                    user.setPassword(MD5Tool_Two.MD5("123456"));
                    user.setUsId(UUID.randomUUID().toString().replace("-", ""));
                    iUserService.insert(user);
                    //给用户绑定默认的运营管理员角色,运营管理员角色为系统数据，固定id为1
                    UserRole userRole = new UserRole();
                    userRole.setUrId(UUID.randomUUID().toString().replace("-", ""));
                    userRole.setUsId(user.getUsId());
                    userRole.setRoId("1");
                    //若该用户是政府用户或者管理员，再绑定监管部门管理员角色，固定ID为2
                    if (jsonResult.get("type") != null && (jsonResult.get("type").equals("gov") || jsonResult.get("type").equals("manager"))) {
                        UserRole userRole2 = new UserRole();
                        userRole2.setUrId(UUID.randomUUID().toString().replace("-", ""));
                        userRole2.setRoId("2");
                        userRole2.setUsId(user.getUsId());
                        //保存用户角色信息
                        iUserRoleService.insert(userRole2);
                    }
                    //保存用户角色信息
                    iUserRoleService.insert(userRole);
                }
                //存储会话用户
                String userId = user.getUsId();
                ConfigClientSessionUser cclSessionUser = getSessionUser(user);
                cclSessionUser.setSessionId(UUID.randomUUID().toString().replace("-",""));
                SimpleSession session = new SimpleSession();
                session.setAttribute(Constants.CONFIG_SESSION_USER, cclSessionUser);
                in.getXboxRequestContext().addSession(cclSessionUser.getSessionId(), session, 86400000 * 7, Constants.CONFIG_SESSION_USER);
                Map resultMap = new HashMap();
                resultMap.put("sessionId", cclSessionUser.getSessionId());
                resultMap.put("userId", userId);
                resultMap.put("userName", user.getLoginName());

                //登录成功
                commonResult.setCode(Constants.CODE_SUCCESS);
                commonResult.setMessage(Constants.CODE_SUCCESS_MSG);
                commonResult.setResult(resultMap);
                //更新user
                iUserService.updateById(user);
            }else{
                //未登录成功
                commonResult.setCode(Constants.CODE_FAIL);
                commonResult.setMessage("未获取到user信息");
                return commonResult;
            }
            logger.info("一体化平台端用户登录->>zhgd.configClient.us.ythUserLogin->>结束");
        }catch (Exception e){
            logger.error("一体化平台端用户登录->>zhgd.configClient.us.ythUserLogin->>异常："+e.getMessage());
            commonResult.setCode(Constants.CODE_FAIL);
            commonResult.setMessage(Constants.CODE_FAIL_MSG);
            in.getXboxRequestContext().setException(new Exception(e.getMessage()));
            e.printStackTrace();
        }
        return commonResult;
    }

    /**
     * 根据user获取ServerSessionUser
     * @param user
     * @return
     */
    private ConfigClientSessionUser getSessionUser(User user) {
        ConfigClientSessionUser cclSessionUser = new ConfigClientSessionUser();
        /**
         * 设置用户基本信息
         */
        cclSessionUser.setUser(user);
        cclSessionUser.setUserId(user.getUsId());

        /**
         * 设置用户直属公司信息
         */
        Company directCompany = iCompanyService.selectById(user.getCompanyId());
        if(directCompany != null){
            cclSessionUser.setDirectCompany(directCompany);

            /**
             * 设置用户所属总公司信息
             */
            Company headCompany = new Company();
            //直属公司有上级公司去查询总公司
            if(directCompany.getParentId() != 0){
                EntityWrapper<Company> ewCompany = new EntityWrapper<>();
                ewCompany.setEntity(new Company());
                ewCompany.eq("compCode", directCompany.getCompCode().substring(0,3));
                List<Company> companyList = iCompanyService.selectList(ewCompany);
                if(companyList != null && companyList.size() > 0){
                    //获取到所属总公司
                    headCompany = companyList.get(0);
                }
            }else {
                headCompany = directCompany;
            }
            cclSessionUser.setHeadCompany(headCompany);
        }

        /**
         * 设置用户所属员工信息
         */
        if(user.getEmId() != null && !user.getEmId().equals("")){
            Employee employee = iEmployeeService.selectDetailById(user.getEmId());
            if(employee != null){
                employee.setProject(null);
                cclSessionUser.setEmployee(employee);
            }
        }

        /**
         * 设置员工角色信息
         */
        List<Role> roleList = iRoleService.getRoleListByUserId(user.getUsId());
        //设置用户最终的数据权限
        cclSessionUser.setRoleList(roleList);
        if(roleList != null && roleList.size() > 0){
            cclSessionUser.setDataScope(roleList.get(0).getDataScopeCD().getPropertyCode());
            for(Role role : roleList){
                if(Integer.valueOf(role.getDataScopeCD().getPropertyCode()) < Integer.valueOf(cclSessionUser.getDataScope())){
                    cclSessionUser.setDataScope(role.getDataScopeCD().getPropertyCode());
                }
            }
        }

        return cclSessionUser;
    }

    /**
     * 获取海康用户列表
     * @param in
     * @return
     */
    @ServiceMethod(method = "zhgd.configClient.us.getHkUserList", title = "获取海康用户列表", version = "1.0", needInSession = NeedInSessionType.YES)
    public CommonResult getHkUserList(CclLoginIn in) {
        CommonResult commonResult = new CommonResult();
        List<Map<String,String>> hkUserMapList = new ArrayList<>();
        try{
            logger.info("获取海康用户列表->>zhgd.configClient.us.getHkUserList->>开始");
            EntityWrapper<HkUser> ewHkUser = new EntityWrapper<HkUser>();
            ewHkUser.setEntity(new HkUser());
            List<HkUser> hkUserList = iHkUserService.selectList(ewHkUser);
            if(hkUserList.size() > 0){
                for(HkUser hkUser : hkUserList){
                    String hkId = hkUser.getUserUuid();
                    String hkName = hkUser.getUserName();
                    Map<String,String> hkMap = new HashMap<>();
                    hkMap.put("value",hkId);
                    hkMap.put("text",hkName);
                    hkUserMapList.add(hkMap);
                }
            }
            commonResult.setCode(Constants.CODE_SUCCESS);
            commonResult.setMessage(Constants.CODE_SUCCESS_MSG);
            commonResult.setResult(hkUserMapList);
            logger.info("获取海康用户列表->>zhgd.configClient.us.getHkUserList->>结束");
        }catch (Exception e){
            logger.error("获取海康用户列表->>zhgd.configClient.us.getHkUserList->>异常："+e.getMessage());
            commonResult.setCode(Constants.CODE_FAIL);
            commonResult.setMessage(Constants.CODE_FAIL_MSG);
            in.getXboxRequestContext().setException(new Exception(e.getMessage()));
            e.printStackTrace();
        }
        return commonResult;
    }
}
